package com.huarui.companypackage.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.PagingInfo;

import com.huarui.companypackage.model.Service;
import com.huarui.companypackage.service.ServerService;
import com.opensymphony.xwork2.Action;

public class ServiceAction extends BaseAction {

	/**
	 *  
	 */
	private static final long serialVersionUID = 8683094568495670949L;
	// private Service service;
	private ServerService serverService;

	public String add() {
		Service service = this.getService();
		this.serverService.addService(service);
		ServletActionContext.getContext().put("jsonResult", service);
		return Action.SUCCESS;
	}

	public String modify() {
		Service service = this.getService();
		this.serverService.modifyService(service);
		ServletActionContext.getContext().put("jsonResult", service);
		return Action.SUCCESS;
	}

	private Service getService() {
		String id = super.getSingleParameter("id");
		String code = super.getSingleParameter("code");
		String name = super.getSingleParameter("name");
		String target = super.getSingleParameter("target");
		Integer selectable = super.getIntegerParameter("selectable", 0);

		Service service = new Service();
		service.setCode(code);
		service.setName(name);
		service.setSelectable(selectable);
		service.setTarget(Integer.parseInt(target));

		if (StringUtils.isNotEmpty(id)) {
			service.setId(Integer.parseInt(id));
		}
		return service;
	}

	public String list() throws Exception {
		PagingInfo<Service, Service> paginInfo = new PagingInfo<Service, Service>();
		int start = super.getIntegerParameter("start", 0);
		int limit = super.getIntegerParameter("limit", 20);
		paginInfo.setStart(start);
		paginInfo.setLimit(limit);
		this.serverService.queryServiceInfos(paginInfo);
		ServletActionContext.getContext().put("jsonResult", paginInfo);
		return Action.SUCCESS;
	}

	public String getSelectableService() {
		Map<String, Object> jsonResult = new HashMap<String, Object>();
		List<Service> services = serverService
				.getSelectableService(Service.SERVICE_SELECTABEL_YES);
		jsonResult.put("root", services);
		ServletActionContext.getContext().put("jsonResult", jsonResult);
		return SUCCESS;
	}

	public void setServerService(ServerService serverService) {
		this.serverService = serverService;
	}

}
